/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.faesa.acervo.business.ejb;

import br.faesa.acervo.entity.Entidade;
import br.faesa.acervo.exception.DataAccessException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author aluno.faesa
 */
public abstract class AcervoDAO <T extends Entidade>{

    @PersistenceContext
    protected EntityManager em;
    
    protected Class entityClass;
    
    protected AcervoDAO(Class<T> entityClass){
        this.entityClass = entityClass;
    }
    
    public boolean isAtachada(Object entidade){
        return this.em.contains(entidade);
    }
    
    public void salvar(T entidade) {

        try {
            em.merge(entidade);

        } catch (Throwable e) {
            e.printStackTrace();
            throw new DataAccessException(e);
        }
    }
    
    public void remove(T entidade) {

        try {
            Object o = entidade;
            if(!em.contains(entidade)){
                o = em.find(entityClass, entidade.getId());
            }
            em.remove(o);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new DataAccessException(e);
        }
    }

    public T merge(T entidade) {

        try {
            return em.merge(entidade);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new DataAccessException(e);
        }
    }

    public List<T> findAll() {
        
        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery cq = cb.createQuery();
        
        cq.select(cq.from(entityClass));
        
        return em.createQuery(cq).getResultList();
    }
    
    public T find(Object id) {
        return (T) em.find(entityClass, id);
    }
    

}
